package com.mimo.admin.shiro.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;

import com.mimo.admin.constants.HttpParams;
import com.mimo.admin.shiro.utils.CurrentAdminUser;

public class SessionTimeoutFilter extends FormAuthenticationFilter {


  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    String userCode = CurrentAdminUser.getUserCode();

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (!StringUtils.hasText(userCode) && HttpParams.XML_HTTP_REQUEST
        .equalsIgnoreCase(httpRequest.getHeader(HttpParams.X_REQUESTED_WITH))) {

      HttpServletResponse httpResponse = (HttpServletResponse) response;
      httpResponse.setCharacterEncoding("UTF-8");
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      httpResponse.addHeader(HttpParams.SESSIONS_TATUS, HttpParams.SESSIONS_TIMEOUT);
      return false;
    }

    return super.onAccessDenied(request, response);
  }

  @Override
  protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    String userCode = CurrentAdminUser.getUserCode();
    if (!StringUtils.hasText(userCode)) { // 如果没有取到值  说明session过期了
      SecurityUtils.getSubject().logout(); // 强制失效登出
      return false;
    }
    return super.isAccessAllowed(request, response, mappedValue);
  }

}
